import React, { useEffect, useState, useCallback } from 'react';
import MethodFilterBar from './MethodFilterBar';
import MethodTable from './MethodTable';
import { fetchMethodPageQuery } from '../../services/method';
import { Spin, Button, Alert, Tabs, Card, Row, Col, Empty, Table } from 'antd';
import { useNavigate } from 'react-router-dom';
import { getUnit } from '../../services/unit';
import { 
    InfoCircleOutlined, 
    FunctionOutlined, 
    DatabaseOutlined, 
    FileTextOutlined, 
    BarChartOutlined,
    ApiOutlined,
    SettingOutlined,
    SyncOutlined,
    CodeOutlined
} from '@ant-design/icons';
import ReactECharts from 'echarts-for-react';

// 时间转换工具函数
const convertDaysToDateQuery = (days: number, baseDate: Date = new Date()) => {
    const cutoffDate = new Date(baseDate);
    cutoffDate.setDate(cutoffDate.getDate() - days);
    
    return {
        dateString: cutoffDate.toISOString().split('T')[0], // YYYY-MM-DD格式
        dateTime: cutoffDate.toISOString(), // 完整ISO格式
        timestamp: cutoffDate.getTime(), // 时间戳
        formatDisplay: `${cutoffDate.getFullYear()}-${String(cutoffDate.getMonth() + 1).padStart(2, '0')}-${String(cutoffDate.getDate()).padStart(2, '0')}`
    };
};

// 格式化查询条件显示
const formatQueryCondition = (field: string, value: any, meta?: any) => {
    switch (field) {
        case 'noSaCallDurationDays':
            return `累计无调用时长 ≥ ${value}天 (即最后调用时间在 ${meta?.noSaCallCutoffDate} 之前)`;
        case 'noCodeChangeDurationDays':
            return `累计无修改时长 ≥ ${value}天 (即最后修改时间在 ${meta?.noCodeChangeCutoffDate} 之前)`;
        case 'serviceType':
            return `服务类型为 ${value}`;
        case 'isEntry':
            return `${value ? '入口' : '非入口'}方法`;
        case 'methodName':
            return `方法名包含 "${value}"`;
        case 'className':
            return `类名包含 "${value}"`;
        case 'packageName':
            return `包名包含 "${value}"`;
        case 'serviceName':
            return `服务名包含 "${value}"`;
        case 'orderBy':
            const orderFieldMap: { [key: string]: string } = {
                'noCodeChangeDurationDays': '累计无修改时间',
                'gitCreateTime': '累计创建时间',
                'noSaCallDurationDays': '累计无调用时长',
                'methodName': '方法名',
                'className': '类名',
                'packageName': '包名'
            };
            const orderTypeMap: { [key: string]: string } = {
                'asc': '升序',
                'desc': '降序'
            };
            const fieldName = orderFieldMap[value] || value;
            const orderType = orderTypeMap[meta?.orderByType] || meta?.orderByType || '降序';
            return `按${fieldName}${orderType}排列`;
        default:
            return `${field}: ${value}`;
    }
};

interface UnitDetailPageProps {
    unitId: string;
}

// 基本信息组件
const BasicInfo: React.FC<{ unitId: string }> = ({ unitId }) => {
    const [unitConfig, setUnitConfig] = useState<any>(null);
    const [unitConfigLoading, setUnitConfigLoading] = useState(false);
    const [statisticsData, setStatisticsData] = useState<any>(null);
    const [statisticsLoading, setStatisticsLoading] = useState(false);
    const [languageData, setLanguageData] = useState<any[]>([]);
    const [languageLoading, setLanguageLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);

    // 加载单元配置信息
    const loadUnitConfig = useCallback(async () => {
        if (!unitId) return;
        
        setUnitConfigLoading(true);
        try {
            const response = await getUnit(unitId);
            const dataRes = (response && response.data) ? response.data : response;
            setUnitConfig(dataRes || null);
        } catch (error: any) {
            console.error('加载单元配置失败:', error);
            setUnitConfig(null);
        } finally {
            setUnitConfigLoading(false);
        }
    }, [unitId]);

    // 加载统计概览数据
    const loadStatistics = useCallback(async () => {
        if (!unitId) return;
        
        setStatisticsLoading(true);
        setError(null);
        
        try {
            // 调用真实的统计概览API
            const { getStatisticsOverview } = await import('../../services/statistics');
            const response: any = await getStatisticsOverview(unitId);
            
            console.log('Statistics API response:', response);
            
            // 处理后端响应格式：BaseResponse<UnitCodeOverviewDTO>
            let statisticsData = null;
            if (response && typeof response === 'object') {
                if ('code' in response && response.code === 0 && response.data) {
                    // 标准BaseResponse格式
                    statisticsData = response.data;
                } else if ('totalFiles' in response || 'totalLines' in response) {
                    // 直接数据格式
                    statisticsData = response;
                } else {
                    console.warn('统计概览数据格式异常:', response);
                }
            }
            
            if (statisticsData) {
                setStatisticsData(statisticsData);
                console.log('Loaded statistics data:', statisticsData);
            } else {
                console.warn('统计概览数据为空');
                setStatisticsData(null);
            }
        } catch (error: any) {
            console.error('加载统计数据失败:', error);
            setError(error?.response?.data?.msg || '加载统计数据失败');
            setStatisticsData(null);
        } finally {
            setStatisticsLoading(false);
        }
    }, [unitId]);

    // 加载语言统计数据
    const loadLanguageData = useCallback(async () => {
        if (!unitId) return;
        
        setLanguageLoading(true);
        try {
            // 调用语言组成接口
            const { getLanguageComposition } = await import('../../services/statistics');
            const response: any = await getLanguageComposition(unitId);
            
            // 验证响应数据
            if (response && Array.isArray(response)) {
                setLanguageData(response);
            } else if (response && response.data && Array.isArray(response.data)) {
                setLanguageData(response.data);
            } else {
                console.warn('语言组成数据格式异常:', response);
                setLanguageData([]);
            }
        } catch (error: any) {
            console.error('加载语言统计数据失败:', error);
            setLanguageData([]);
        } finally {
            setLanguageLoading(false);
        }
    }, [unitId]);

    useEffect(() => {
        loadUnitConfig();
        loadStatistics();
        loadLanguageData();
    }, [loadUnitConfig, loadStatistics, loadLanguageData]);

    const isLoading = unitConfigLoading || statisticsLoading;

    if (isLoading) {
        return (
            <div style={{ textAlign: 'center', padding: '40px' }}>
                <Spin size="large" />
                <div style={{ marginTop: '16px' }}>加载基本信息中...</div>
            </div>
        );
    }

    if (error) {
        return (
            <Alert 
                message="加载失败" 
                description={error}
                type="error" 
                showIcon 
                action={
                    <Button size="small" onClick={loadStatistics}>
                        重试
                    </Button>
                }
            />
        );
    }

    return (
        <div>
            {/* 单元基本信息 */}
            <Card 
                title={
                    <span>
                        <SettingOutlined style={{ marginRight: 8, color: '#1890ff' }} />
                        单元基本信息
                    </span>
                }
                style={{ marginBottom: '24px' }}
                extra={
                    <Button 
                        size="small" 
                        onClick={() => {
                            loadUnitConfig();
                            loadStatistics();
                        }} 
                        loading={isLoading}
                        icon={<SyncOutlined />}
                    >
                        刷新
                    </Button>
                }
            >
                {unitConfig ? (
                    <Row gutter={[24, 16]}>
                        <Col span={12}>
                            <div style={{ padding: '16px 0' }}>
                                <h4 style={{ marginBottom: '16px', color: '#333', fontWeight: '600' }}>基本信息</h4>
                                <div style={{ lineHeight: '2.2' }}>
                                    <div><span style={{ color: '#666', fontWeight: '500' }}>单元ID：</span><span style={{ color: '#333' }}>{unitConfig.unitId || '-'}</span></div>
                                    <div><span style={{ color: '#666', fontWeight: '500' }}>应用ID：</span><span style={{ color: '#333' }}>{unitConfig.appId || '-'}</span></div>
                                    <div><span style={{ color: '#666', fontWeight: '500' }}>单元类型：</span><span style={{ color: '#333' }}>{unitConfig.unitType || '-'}</span></div>
                                    <div><span style={{ color: '#666', fontWeight: '500' }}>所属团队：</span><span style={{ color: '#333' }}>{unitConfig.ownTeam || '-'}</span></div>
                                    <div><span style={{ color: '#666', fontWeight: '500' }}>所属中心：</span><span style={{ color: '#333' }}>{unitConfig.ownCenter || '-'}</span></div>
                                </div>
                            </div>
                        </Col>
                        <Col span={12}>
                            <div style={{ padding: '16px 0' }}>
                                <h4 style={{ marginBottom: '16px', color: '#333', fontWeight: '600' }}>代码仓库</h4>
                                <div style={{ lineHeight: '2.2' }}>
                                    <div>
                                        <span style={{ color: '#666', fontWeight: '500' }}>Git仓库：</span>
                                        {unitConfig.gitRepoUrl ? (
                                            <a href={unitConfig.gitRepoUrl} target="_blank" rel="noopener noreferrer" style={{ color: '#1890ff' }}>
                                                {unitConfig.gitRepoUrl}
                                            </a>
                                        ) : (
                                            <span style={{ color: '#333' }}>-</span>
                                        )}
                                    </div>
                                    <div><span style={{ color: '#666', fontWeight: '500' }}>当前分支：</span><span style={{ color: '#333' }}>{unitConfig.currentBranch || unitConfig.defaultBranch || 'master'}</span></div>
                                    <div><span style={{ color: '#666', fontWeight: '500' }}>默认分支：</span><span style={{ color: '#333' }}>{unitConfig.defaultBranch || 'master'}</span></div>
                                    <div><span style={{ color: '#666', fontWeight: '500' }}>当前版本：</span><span style={{ color: '#1890ff' }}>{unitConfig.currentCommitId || unitConfig.currentVersion || '2595eb1b'}</span></div>
                                </div>
                            </div>
                        </Col>
                    </Row>
                ) : (
                    <div style={{ textAlign: 'center', padding: '40px' }}>
                        <Empty description="暂无配置信息" />
                    </div>
                )}
            </Card>

            {/* 统计概览信息 */}
            <Card 
                title={
                    <span>
                        <BarChartOutlined style={{ marginRight: 8, color: '#1890ff' }} />
                        统计概览信息
                    </span>
                }
                style={{ marginBottom: '24px' }}
            >
                {statisticsData ? (
                    <div>
                        <Row gutter={[24, 24]} style={{ marginBottom: 32 }}>
                            <Col span={8}>
                                <div style={{ textAlign: 'center', padding: '20px', backgroundColor: '#f8fbff', borderRadius: '8px', border: '1px solid #e6f4ff' }}>
                                    <div style={{ fontSize: '28px', fontWeight: 'bold', color: '#1890ff', marginBottom: '8px' }}>
                                        <FileTextOutlined style={{ marginRight: '8px' }} />
                                        {statisticsData.totalFiles || 0}
                                    </div>
                                    <div style={{ color: '#666', fontSize: '14px' }}>总文件数</div>
                                </div>
                            </Col>
                            <Col span={8}>
                                <div style={{ textAlign: 'center', padding: '20px', backgroundColor: '#f6ffed', borderRadius: '8px', border: '1px solid #d9f7be' }}>
                                    <div style={{ fontSize: '28px', fontWeight: 'bold', color: '#52c41a', marginBottom: '8px' }}>
                                        <CodeOutlined style={{ marginRight: '8px' }} />
                                        {(statisticsData.totalLines || 0).toLocaleString()}
                                    </div>
                                    <div style={{ color: '#666', fontSize: '14px' }}>总代码行数</div>
                                </div>
                            </Col>
                            <Col span={8}>
                                <div style={{ textAlign: 'center', padding: '20px', backgroundColor: '#fafbff', borderRadius: '8px', border: '1px solid #e6ebf7' }}>
                                    <div style={{ fontSize: '28px', fontWeight: 'bold', color: '#722ed1', marginBottom: '8px' }}>
                                        <CodeOutlined style={{ marginRight: '8px' }} />
                                        {(statisticsData.totalCodeLines || 0).toLocaleString()}
                                    </div>
                                    <div style={{ color: '#666', fontSize: '14px' }}>有效代码行数</div>
                                </div>
                            </Col>
                        </Row>

                        <Row gutter={[24, 16]}>
                            <Col span={12}>
                                <div style={{ textAlign: 'center', padding: '24px', backgroundColor: '#fafafa', borderRadius: '8px' }}>
                                    <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#1890ff', marginBottom: '8px' }}>
                                        {statisticsData.techStack || 'SpringBoot'}
                                    </div>
                                    <div style={{ color: '#666', fontSize: '14px' }}>主要技术栈</div>
                                </div>
                            </Col>
                            <Col span={12}>
                                <div style={{ textAlign: 'center', padding: '24px', backgroundColor: '#fafafa', borderRadius: '8px' }}>
                                    <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#52c41a', marginBottom: '8px' }}>
                                        {statisticsData.mainLanguage || 'Java'}
                                    </div>
                                    <div style={{ color: '#666', fontSize: '14px' }}>主要编程语言</div>
                                </div>
                            </Col>
                        </Row>
                    </div>
                ) : (
                    <div style={{ textAlign: 'center', padding: '40px' }}>
                        <Empty description="暂无统计数据" />
                    </div>
                )}
            </Card>

            {/* 语言统计信息 */}
            <Card 
                title={
                    <span>
                        <CodeOutlined style={{ marginRight: 8, color: '#1890ff' }} />
                        语言统计信息
                    </span>
                }
                extra={
                    <Button 
                        size="small" 
                        onClick={loadLanguageData} 
                        loading={languageLoading}
                        icon={<SyncOutlined />}
                    >
                        刷新
                    </Button>
                }
            >
                {languageLoading ? (
                    <div style={{ textAlign: 'center', padding: '40px' }}>
                        <Spin size="large" />
                        <div style={{ marginTop: '16px' }}>加载语言统计中...</div>
                    </div>
                ) : languageData && languageData.length > 0 ? (
                    <Row gutter={24}>
                        {/* 左侧：饼图展示 */}
                        <Col span={12}>
                            <div style={{ padding: '20px 0' }}>
                                <h4 style={{ textAlign: 'center', marginBottom: '24px', color: '#333' }}>语言分布</h4>
                                <div style={{ height: '300px' }}>
                                    <ReactECharts
                                        option={{
                                            tooltip: {
                                                trigger: 'item',
                                                formatter: '{b}: {c} ({d}%)'
                                            },
                                            legend: {
                                                show: false
                                            },
                                            series: [
                                                {
                                                    type: 'pie',
                                                    radius: ['40%', '70%'],
                                                    center: ['50%', '50%'],
                                                    avoidLabelOverlap: false,
                                                    itemStyle: {
                                                        borderRadius: 6,
                                                        borderColor: '#fff',
                                                        borderWidth: 3
                                                    },
                                                    label: {
                                                        show: true,
                                                        fontSize: 12,
                                                        fontWeight: 'bold',
                                                        formatter: '{b}\n{d}%'
                                                    },
                                                    emphasis: {
                                                        label: {
                                                            show: true,
                                                            fontSize: 16,
                                                            fontWeight: 'bold'
                                                        }
                                                    },
                                                    data: languageData.map((lang: any, index: number) => {
                                                        const colors = ['#8B4513', '#808080', '#1890ff', '#f5222d', '#52c41a', '#faad14'];
                                                        return {
                                                            value: lang.totalLines,
                                                            name: lang.language,
                                                            itemStyle: {
                                                                color: colors[index] || '#d4d4d4'
                                                            }
                                                        };
                                                    })
                                                }
                                            ]
                                        }}
                                        style={{ height: '100%', width: '100%' }}
                                        opts={{ renderer: 'canvas' }}
                                    />
                                </div>
                            </div>
                        </Col>
                        
                        {/* 右侧：表格展示 */}
                        <Col span={12}>
                            <div style={{ padding: '20px 0' }}>
                                <Table
                                    dataSource={languageData.map((lang: any, index: number) => {
                                        const colors = ['#8B4513', '#808080', '#1890ff', '#f5222d', '#52c41a', '#faad14'];
                                        return {
                                            key: index.toString(),
                                            language: lang.language,
                                            files: lang.fileCount,
                                            lines: lang.totalLines,
                                            percentage: lang.percentage,
                                            color: colors[index] || '#d4d4d4'
                                        };
                                    })}
                                    columns={[
                                        {
                                            title: '语言',
                                            dataIndex: 'language',
                                            key: 'language',
                                            render: (text: string, record: any) => (
                                                <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                                                    <div 
                                                        style={{ 
                                                            width: '12px', 
                                                            height: '12px', 
                                                            borderRadius: '50%', 
                                                            backgroundColor: record.color 
                                                        }} 
                                                    />
                                                    <span style={{ fontWeight: '500' }}>{text}</span>
                                                </div>
                                            )
                                        },
                                        {
                                            title: '文件数',
                                            dataIndex: 'files',
                                            key: 'files',
                                            align: 'center' as const,
                                            render: (value: number) => (
                                                <span style={{ color: '#333' }}>{value}</span>
                                            )
                                        },
                                        {
                                            title: '代码行数',
                                            dataIndex: 'lines',
                                            key: 'lines',
                                            align: 'center' as const,
                                            render: (value: number) => (
                                                <span style={{ fontWeight: '600', color: '#333' }}>{value}</span>
                                            )
                                        },
                                        {
                                            title: '占比',
                                            dataIndex: 'percentage',
                                            key: 'percentage',
                                            align: 'center' as const,
                                            render: (value: number) => (
                                                <span style={{ color: '#1890ff', fontWeight: '600' }}>{value.toFixed(1)}%</span>
                                            )
                                        }
                                    ]}
                                    pagination={false}
                                    size="small"
                                    showHeader={true}
                                    style={{ marginTop: '24px' }}
                                />
                            </div>
                        </Col>
                    </Row>
                ) : (
                    <div style={{ textAlign: 'center', padding: '40px' }}>
                        <Empty description="暂无语言统计数据" />
                    </div>
                )}
            </Card>
        </div>
    );
};

// API分析组件
const ApiAnalysis: React.FC = () => {
    return (
        <div style={{ padding: '24px', textAlign: 'center' }}>
            <Empty 
                description="API分析功能开发中..." 
                image={Empty.PRESENTED_IMAGE_SIMPLE}
            />
        </div>
    );
};

// 生成完整项目结构的模拟数据
const generateMockScaleData = () => {
  const files = [
    // Java源代码文件
    { path: 'src/main/java/com/codeknowledge/controller/UserController.java', lines: 2340 },
    { path: 'src/main/java/com/codeknowledge/controller/OrderController.java', lines: 1890 },
    { path: 'src/main/java/com/codeknowledge/controller/ProductController.java', lines: 1450 },
    { path: 'src/main/java/com/codeknowledge/controller/PaymentController.java', lines: 1200 },
    { path: 'src/main/java/com/codeknowledge/controller/AdminController.java', lines: 980 },
    { path: 'src/main/java/com/codeknowledge/controller/ReportController.java', lines: 760 },
    { path: 'src/main/java/com/codeknowledge/controller/BaseController.java', lines: 330 },
    
    { path: 'src/main/java/com/codeknowledge/service/UserService.java', lines: 3200 },
    { path: 'src/main/java/com/codeknowledge/service/OrderService.java', lines: 2850 },
    { path: 'src/main/java/com/codeknowledge/service/ProductService.java', lines: 2400 },
    { path: 'src/main/java/com/codeknowledge/service/PaymentService.java', lines: 2100 },
    { path: 'src/main/java/com/codeknowledge/service/NotificationService.java', lines: 1800 },
    { path: 'src/main/java/com/codeknowledge/service/EmailService.java', lines: 1450 },
    { path: 'src/main/java/com/codeknowledge/service/AuthService.java', lines: 1200 },
    { path: 'src/main/java/com/codeknowledge/service/CacheService.java', lines: 620 },
    
    { path: 'src/main/java/com/codeknowledge/repository/UserRepository.java', lines: 1890 },
    { path: 'src/main/java/com/codeknowledge/repository/OrderRepository.java', lines: 1560 },
    { path: 'src/main/java/com/codeknowledge/repository/ProductRepository.java', lines: 1330 },
    { path: 'src/main/java/com/codeknowledge/repository/PaymentRepository.java', lines: 980 },
    { path: 'src/main/java/com/codeknowledge/repository/ConfigRepository.java', lines: 720 },
    { path: 'src/main/java/com/codeknowledge/repository/LogRepository.java', lines: 300 },
    
    { path: 'src/main/java/com/codeknowledge/model/User.java', lines: 780 },
    { path: 'src/main/java/com/codeknowledge/model/Order.java', lines: 650 },
    { path: 'src/main/java/com/codeknowledge/model/Product.java', lines: 590 },
    { path: 'src/main/java/com/codeknowledge/model/Payment.java', lines: 480 },
    { path: 'src/main/java/com/codeknowledge/model/Category.java', lines: 420 },
    { path: 'src/main/java/com/codeknowledge/model/Address.java', lines: 320 },
    { path: 'src/main/java/com/codeknowledge/model/BaseEntity.java', lines: 240 },
    
    { path: 'src/main/java/com/codeknowledge/config/DatabaseConfig.java', lines: 450 },
    { path: 'src/main/java/com/codeknowledge/config/SecurityConfig.java', lines: 380 },
    { path: 'src/main/java/com/codeknowledge/config/RedisConfig.java', lines: 320 },
    { path: 'src/main/java/com/codeknowledge/config/WebConfig.java', lines: 290 },
    
    { path: 'src/main/java/com/codeknowledge/Application.java', lines: 120 },
    
    // 测试代码
    { path: 'src/test/java/com/codeknowledge/controller/UserControllerTest.java', lines: 850 },
    { path: 'src/test/java/com/codeknowledge/service/UserServiceTest.java', lines: 920 },
    { path: 'src/test/java/com/codeknowledge/repository/UserRepositoryTest.java', lines: 680 },
    { path: 'src/test/java/com/codeknowledge/ApplicationTest.java', lines: 240 },
    
    // 资源文件
    { path: 'src/main/resources/application.yml', lines: 120 },
    { path: 'src/main/resources/application-dev.yml', lines: 85 },
    { path: 'src/main/resources/application-prod.yml', lines: 95 },
    { path: 'src/main/resources/logback-spring.xml', lines: 180 },
    { path: 'src/main/resources/banner.txt', lines: 12 },
    
    { path: 'src/main/resources/static/css/style.css', lines: 450 },
    { path: 'src/main/resources/static/js/main.js', lines: 320 },
    { path: 'src/main/resources/static/js/utils.js', lines: 180 },
    
    { path: 'src/main/resources/templates/index.html', lines: 85 },
    { path: 'src/main/resources/templates/error.html', lines: 45 },
    
    { path: 'src/main/resources/db/migration/V1__Init_database.sql', lines: 280 },
    { path: 'src/main/resources/db/migration/V2__Add_user_table.sql', lines: 95 },
    
    // 测试资源
    { path: 'src/test/resources/application-test.yml', lines: 65 },
    { path: 'src/test/resources/test-data.sql', lines: 150 },
    
    // 项目配置文件
    { path: 'pom.xml', lines: 320 },
    { path: 'README.md', lines: 180 },
    { path: '.gitignore', lines: 45 },
    { path: 'Dockerfile', lines: 35 },
    { path: 'docker-compose.yml', lines: 85 },
    
    // 配置目录
    { path: 'config/checkstyle.xml', lines: 150 },
    { path: 'config/spotbugs-exclude.xml', lines: 85 },
    
    // 脚本文件
    { path: 'scripts/build.sh', lines: 65 },
    { path: 'scripts/deploy.sh', lines: 120 },
    { path: 'scripts/start.sh', lines: 45 },
    { path: 'scripts/stop.sh', lines: 25 },
    
    // 文档
    { path: 'docs/API.md', lines: 450 },
    { path: 'docs/DEPLOYMENT.md', lines: 280 },
    { path: 'docs/CHANGELOG.md', lines: 320 },
    
    // 前端资源 (如果是全栈项目)
    { path: 'frontend/src/App.js', lines: 280 },
    { path: 'frontend/src/index.js', lines: 45 },
    { path: 'frontend/src/components/Header.js', lines: 120 },
    { path: 'frontend/src/components/Footer.js', lines: 85 },
    { path: 'frontend/src/utils/api.js', lines: 180 },
    { path: 'frontend/package.json', lines: 65 },
    { path: 'frontend/README.md', lines: 95 }
  ];
  
  return { files };
};

const mockScaleData = generateMockScaleData();

// 代码规模分析组件
const CodeScaleAnalysis: React.FC<{ unitId: string }> = ({ unitId }) => {
  const [scaleData, setScaleData] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [chartType, setChartType] = useState<'treemap' | 'sunburst'>('treemap');
  const [volumeTopData, setVolumeTopData] = useState<any>(null);
  const [volumeTopLoading, setVolumeTopLoading] = useState(false);
  const [unitInfo, setUnitInfo] = useState<any>(null);

  // 构建Gitee代码仓库链接的工具函数
  const buildGiteeLink = (filePath: string, startLine?: number, endLine?: number): string => {
    if (!unitInfo?.gitRepoUrl || !filePath) return '';
    
    // 清理仓库URL，去掉.git后缀
    const baseRepoUrl = unitInfo.gitRepoUrl.replace(/\.git$/i, '');
    const branch = unitInfo.currentBranch || unitInfo.defaultBranch || 'master';
    
    // 构建文件路径URL
    let giteeUrl = '';
    if (/gitee\.com/i.test(baseRepoUrl)) {
      // Gitee格式：https://gitee.com/owner/repo/blob/branch/path/to/file
      giteeUrl = `${baseRepoUrl}/blob/${branch}/${filePath}`;
    } else if (/github\.com/i.test(baseRepoUrl)) {
      // GitHub格式
      giteeUrl = `${baseRepoUrl}/blob/${branch}/${filePath}`;
    } else if (/gitlab/i.test(baseRepoUrl)) {
      // GitLab格式
      giteeUrl = `${baseRepoUrl}/-/blob/${branch}/${filePath}`;
    } else {
      // 默认Gitee格式
      giteeUrl = `${baseRepoUrl}/blob/${branch}/${filePath}`;
    }
    
    // 添加行号锚点
    if (startLine) {
      if (endLine && endLine !== startLine) {
        giteeUrl += `#L${startLine}-L${endLine}`;
      } else {
        giteeUrl += `#L${startLine}`;
      }
    }
    
    return giteeUrl;
  };

  // 加载单元信息
  const loadUnitInfo = useCallback(async () => {
    if (!unitId) return;
    try {
      const { getUnit } = await import('../../services/unit');
      const response = await getUnit(unitId);
      const dataRes = (response && response.data) ? response.data : response;
      setUnitInfo(dataRes || null);
    } catch (error: any) {
      console.error('加载单元信息失败:', error);
      setUnitInfo(null);
    }
  }, [unitId]);

  // 加载代码规模数据
  const loadScaleData = useCallback(async () => {
    if (!unitId) return;
    
    setLoading(true);
    try {
      // 调用真实的树图文件API
      const { getTreemapFiles } = await import('../../services/statistics');
      const response = await getTreemapFiles(unitId);
      
      console.log('API response:', response);
      
      // 处理后端响应格式：可能是 BaseResponse<FileTreeNodeDTO[]> 或 FileTreeNodeDTO[]
      let fileList: any[] = [];
      if (response && typeof response === 'object') {
        if ('code' in response && response.code === 0 && Array.isArray(response.data)) {
          // 标准BaseResponse格式
          fileList = response.data;
        } else if (Array.isArray(response)) {
          // 直接数组格式
          fileList = response;
        } else {
          console.warn('未识别的响应格式:', response);
          setScaleData(generateMockScaleData());
          return;
        }
      } else if (Array.isArray(response)) {
        fileList = response;
      }
      
      // 验证文件列表数据
      if (Array.isArray(fileList) && fileList.length > 0) {
        // 转换后端数据格式为前端需要的格式
        const transformedFiles = fileList.map((item: any) => ({
          path: item.path,           // 后端字段名
          lines: item.lines,         // 后端字段名  
          size: item.size,           // 后端字段名
          language: item.lang        // 后端字段名为 lang，转换为 language
        }));
        setScaleData({ files: transformedFiles });
        console.log('Loaded treemap files from API:', {
          count: transformedFiles.length,
          sample: transformedFiles[0],
          rawSample: fileList[0]
        });
      } else {
        console.warn('树图文件数据为空或格式错误:', fileList);
        // 如果API失败，使用备用的模拟数据
        setScaleData(generateMockScaleData());
      }
    } catch (error) {
      console.error('加载代码规模数据失败:', error);
      // 如果API失败，使用备用的模拟数据
      setScaleData(generateMockScaleData());
    } finally {
      setLoading(false);
    }
  }, [unitId]);

  // 加载体量Top数据 - 简化版本
  const loadVolumeTopData = useCallback(async () => {
    if (!unitId) return;
    
    setVolumeTopLoading(true);
    try {
      const { getVolumeTopClasses, getVolumeTopMethods } = await import('../../services/statistics');
      
      // 并行请求文件和方法的Top数据
      const [classesResponse, methodsResponse] = await Promise.all([
        getVolumeTopClasses(unitId),
        getVolumeTopMethods(unitId)
      ]);
      
      // 处理响应数据格式
      let classesData: any[] = [];
      let methodsData: any[] = [];
      
      // 解析类数据
      if (classesResponse && typeof classesResponse === 'object') {
        if ('code' in classesResponse && classesResponse.code === 0 && Array.isArray(classesResponse.data)) {
          classesData = classesResponse.data;
        } else if (Array.isArray(classesResponse)) {
          classesData = classesResponse;
        }
      }
      
      // 解析方法数据  
      if (methodsResponse && typeof methodsResponse === 'object') {
        if ('code' in methodsResponse && methodsResponse.code === 0 && Array.isArray(methodsResponse.data)) {
          methodsData = methodsResponse.data;
        } else if (Array.isArray(methodsResponse)) {
          methodsData = methodsResponse;
        }
      }
      
      setVolumeTopData({
        classes: classesData || [],
        methods: methodsData || []
      });
      
      console.log('Loaded volume top data from API:', {
        classes: classesData?.length || 0,
        methods: methodsData?.length || 0
      });
      
    } catch (error: any) {
      console.error('加载体量Top数据失败:', error);
      setVolumeTopData({ classes: [], methods: [] });
    } finally {
      setVolumeTopLoading(false);
    }
  }, [unitId]);

  useEffect(() => {
    if (unitId) {
      loadUnitInfo();
      loadScaleData();
      loadVolumeTopData();
    }
  }, [unitId, loadUnitInfo, loadScaleData, loadVolumeTopData]);

  // treemap 层级视觉（参考 ECharts Disk Usage 示例）
  const getLevelOption = () => ([
    {
      itemStyle: { borderColor: '#777', borderWidth: 0, gapWidth: 1 },
      upperLabel: { show: false }
    },
    {
      itemStyle: { borderColor: '#555', borderWidth: 4, gapWidth: 1 },
      emphasis: { itemStyle: { borderColor: '#ddd' } }
    },
    {
      colorSaturation: [0.35, 0.6],
      itemStyle: { borderWidth: 4, gapWidth: 1, borderColorSaturation: 0.6 }
    }
  ]);

  // 准备树图数据（基于真实 API 数据的文件系统路径层级结构）
  const getTreemapData = () => {
    if (!scaleData || !scaleData.files) return [];
    
    // 构建文件系统路径层次结构
    const buildFileSystemHierarchy = () => {
      const root = { name: 'project', children: [] as any[], value: 0 };
      
      scaleData.files.forEach((file: any) => {
        const filePath = file.path;
        const pathParts = filePath.split('/').filter((part: string) => part.length > 0); // 过滤空字符串
        const lines = file.lines || 0;
        
        let current = root;
        
        // 遍历路径的每一层，构建完整的目录结构
        for (let i = 0; i < pathParts.length; i++) {
          const part = pathParts[i];
          const isLastLevel = (i === pathParts.length - 1);
          const currentPath = pathParts.slice(0, i + 1).join('/');
          
          let existing = current.children.find((child: any) => child.name === part);
          if (!existing) {
            existing = { 
              name: part,
              fullPath: currentPath,
              children: isLastLevel ? undefined : [],
              value: isLastLevel ? lines : 0,
              isFile: isLastLevel,
              isDirectory: !isLastLevel,
              level: i,
              // 为文件添加额外信息
              ...(isLastLevel && {
                fileName: part,
                originalLines: lines,
                fileExtension: part.includes('.') ? part.split('.').pop() || '' : '',
                language: file.language || '',
                fileSize: file.size || 0
              })
            };
            current.children.push(existing);
          } else if (isLastLevel) {
            // 如果是同名文件，累加行数
            existing.value += lines;
            existing.originalLines = (existing.originalLines || 0) + lines;
          }
          current = existing;
        }
      });
      
      // 递归计算每个目录节点的总价值
      const calculateValues = (node: any): number => {
        if (node.isFile) {
          return node.value || 0;
        }
        
        if (node.children && node.children.length > 0) {
          node.value = node.children.reduce((sum: number, child: any) => sum + calculateValues(child), 0);
        }
        return node.value || 0;
      };
      
      calculateValues(root);
      
      // 添加调试信息
      console.log('Generated file system treemap data from real API:', {
        totalFiles: scaleData.files.length,
        rootChildren: root.children.length,
        sampleFile: scaleData.files[0],
        sampleNode: root.children[0],
        rootValue: root.value
      });
      
      return root.children || [];
    };

    return buildFileSystemHierarchy();
  };

  // 计算目录下的文件数量
  const countFiles = (node: any): number => {
    if (node.isFile) return 1;
    if (!node.children) return 0;
    return node.children.reduce((count: number, child: any) => count + countFiles(child), 0);
  };

  // 获取树图配置
  const getTreemapOption = () => {
    const data = getTreemapData();
    
    if (!data || data.length === 0) {
      console.warn('No treemap data available');
      return {
        title: {
          text: '暂无数据',
          left: 'center',
          top: 'middle'
        }
      };
    }
    
    return {
      tooltip: {
        trigger: 'item',
        formatter: (params: any) => {
          const data = params.data;
          if (data.isFile) {
            const lines = [
              `<strong>${data.name}</strong>`,
              `路径: ${data.fullPath}`,
              `代码行数: <span style="color: #1890ff">${params.value.toLocaleString()}</span>`
            ];
            
            // 添加API返回的额外信息
            if (data.fileSize !== undefined && data.fileSize > 0) {
              const sizeKB = (data.fileSize / 1024).toFixed(1);
              lines.push(`文件大小: <span style="color: #52c41a">${sizeKB} KB</span>`);
            }
            if (data.language) {
              lines.push(`语言: <span style="color: #722ed1">${data.language}</span>`);
            }
            
            return lines.join('<br/>');
          } else if (data.isDirectory) {
            const fileCount = countFiles(data);
            return `<strong>${data.name}/</strong><br/>
                    路径: ${data.fullPath}<br/>
                    包含文件: ${fileCount} 个<br/>
                    总代码行数: <span style="color: #1890ff">${params.value.toLocaleString()}</span>`;
          } else {
            return `<strong>${data.fullPath || data.name}</strong><br/>
                    代码行数: <span style="color: #1890ff">${params.value.toLocaleString()}</span>`;
          }
        },
        backgroundColor: 'rgba(255, 255, 255, 0.95)',
        borderColor: '#ddd',
        borderWidth: 1,
        textStyle: { fontSize: 12 }
      },
      series: [{
        name: '代码体量',
        type: 'treemap',
        id: 'code-size',
        universalTransition: true,
        data: data,
        width: '100%',
        height: '100%',
        roam: true,
        nodeClick: 'zoomToNode',
        colorMappingBy: 'value',
        color: [
          '#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', 
          '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf',
          '#aec7e8', '#ffbb78', '#98df8a', '#ff9896', '#c5b0d5'
        ],
        breadcrumb: {
          show: false
        },
        label: { 
          show: true, 
          formatter: (params: any) => {
            // 根据节点类型显示不同的标签
            if (params.data.isFile) {
              // 文件节点：显示文件名（简化显示）
              const fileName = params.data.name;
              return fileName.length > 20 ? fileName.substring(0, 17) + '...' : fileName;
            } else if (params.data.isDirectory) {
              // 目录节点：显示目录名
              return params.data.name;
            }
            return params.data.name;
          },
          fontSize: (params: any) => {
            // 根据节点大小调整字体大小
            const area = params.rect.width * params.rect.height;
            if (area > 15000) return 14;
            if (area > 8000) return 12;
            if (area > 3000) return 10;
            if (area > 1000) return 8;
            return 0; // 太小的区域不显示文字
          },
          color: '#333'
        },
        upperLabel: {
          show: true,
          height: 20,
          color: '#fff',
          fontWeight: 'bold',
          formatter: (params: any) => {
            if (params.data.isDirectory) {
              return `${params.data.name}/`;
            }
            return params.data.name;
          },
          backgroundColor: 'rgba(0,0,0,0.7)'
        },
        visibleMin: 30, // 降低最小可见值，显示更多小文件
        leafDepth: null,
        itemStyle: {
          borderColor: '#fff',
          borderWidth: 2,
          gapWidth: 1,
          shadowColor: 'rgba(0,0,0,0.1)',
          shadowBlur: 2
        },
        levels: getLevelOption()
      }]
    };
  };

  // 获取旭日图配置
  const getSunburstOption = () => {
    const data = getTreemapData();
    
    if (!data || data.length === 0) {
      console.warn('No sunburst data available');
      return {
        title: {
          text: '暂无数据',
          left: 'center',
          top: 'middle'
        }
      };
    }
    
    // 为旭日图数据添加颜色
    const addColorsToSunburstData = (nodes: any[], level = 0): any[] => {
      const colors = [
        // 第一层包颜色（较深）
        ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f'],
        // 第二层包颜色（中等）
        ['#aec7e8', '#ffbb78', '#98df8a', '#ff9896', '#c5b0d5', '#c49c94', '#f7b6d3', '#c7c7c7'],
        // 第三层包颜色（较浅）
        ['#dbdbef', '#ffd8b1', '#c4e6c3', '#ffcccb', '#e2d5f1', '#ddbea9', '#fce4ec', '#f5f5f5'],
        // 文件层颜色（最浅，带透明度）
        ['#e8f4f8', '#fff4e6', '#f0f8e8', '#ffe8e8', '#f4f0f8', '#f0ebe6', '#fdf2f8', '#fafafa']
      ];
      
      return nodes.map((node, index) => {
        const colorPalette = colors[Math.min(level, colors.length - 1)];
        const color = colorPalette[index % colorPalette.length];
        
        const newNode = {
          ...node,
          itemStyle: {
            color: color,
            borderColor: 'rgba(255,255,255,0.8)',
            borderWidth: level === 0 ? 2 : 1
          }
        };
        
        if (node.children && node.children.length > 0) {
          newNode.children = addColorsToSunburstData(node.children, level + 1);
        }
        
        return newNode;
      });
    };
    
    const coloredData = addColorsToSunburstData(data);
    
    return {
      tooltip: {
        trigger: 'item',
        formatter: (params: any) => {
          const data = params.data;
          if (data.isFile) {
            const lines = [
              `<strong>${data.name}</strong>`,
              `路径: ${data.fullPath}`,
              `总行数: <span style="color: #1890ff">${params.value.toLocaleString()}</span>`
            ];
            
            // 添加API返回的额外信息
            if (data.codeLines !== undefined) {
              lines.push(`代码行数: <span style="color: #52c41a">${data.codeLines.toLocaleString()}</span>`);
            }
            if (data.language) {
              lines.push(`语言: <span style="color: #722ed1">${data.language}</span>`);
            }
            
            return lines.join('<br/>');
          } else {
            return `<strong>${data.fullPath || params.name}</strong><br/>
                    代码行数: <span style="color: #1890ff">${params.value.toLocaleString()}</span>`;
          }
        },
        backgroundColor: 'rgba(255, 255, 255, 0.95)',
        borderColor: '#ddd',
        borderWidth: 1,
        textStyle: { fontSize: 12 }
      },
      series: [{
        type: 'sunburst',
        id: 'code-size',
        radius: ['15%', '90%'],
        center: ['50%', '52%'],
        animationDurationUpdate: 600,
        nodeClick: undefined,
        universalTransition: true,
        data: coloredData,
        itemStyle: { 
          borderWidth: 1, 
          borderColor: 'rgba(255,255,255,0.8)',
          shadowColor: 'rgba(0,0,0,0.1)',
          shadowBlur: 3
        },
        label: {
          show: true,
          position: 'inside',
          formatter: (params: any) => {
            // 只显示叶子节点（文件）的名称，且名称较短时才显示
            if (params.data.isFile && params.data.name.length < 20) {
              return params.data.name.replace('.java', '');
            }
            return '';
          },
          fontSize: 10,
          color: '#333'
        },
        emphasis: {
          focus: 'ancestor',
          label: {
            show: true,
            fontSize: 12,
            fontWeight: 'bold'
          },
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        levels: [
          {},
          {
            r0: '15%',
            r: '35%',
            itemStyle: {
              borderWidth: 2,
              borderColor: 'rgba(255,255,255,0.9)'
            },
            label: {
              rotate: 'tangential',
              fontSize: 11,
              color: '#fff',
              fontWeight: 'bold'
            }
          },
          {
            r0: '35%',
            r: '60%',
            itemStyle: {
              borderWidth: 1,
              borderColor: 'rgba(255,255,255,0.8)'
            },
            label: {
              rotate: 'tangential',
              fontSize: 10,
              color: '#333'
            }
          },
          {
            r0: '60%',
            r: '90%',
            label: {
              position: 'outside',
              padding: 3,
              silent: false,
              fontSize: 9,
              color: '#666'
            },
            itemStyle: {
              borderWidth: 1,
              borderColor: 'rgba(255,255,255,0.6)'
            }
          }
        ]
      }]
    };
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '40px' }}>
        <Spin size="large" />
        <div style={{ marginTop: '16px' }}>加载代码规模数据中...</div>
      </div>
    );
  }

  if (!scaleData) {
    return (
      <div style={{ textAlign: 'center', padding: '40px' }}>
        <Empty description="暂无代码规模数据" />
      </div>
    );
  }

  // 组装类级别数据Top10（基于真实API数据），按总行数降序排序
  const topClassesData = (() => {
    if (volumeTopData?.classes && Array.isArray(volumeTopData.classes)) {
      return volumeTopData.classes
        .sort((a: any, b: any) => (b.totalLines || 0) - (a.totalLines || 0))
        .map((item: any, idx: number) => {
          // 处理包名：如果以"java."开头，则从java后面开始显示
          let displayPackageName = item.packageName || '';
          if (displayPackageName.startsWith('java.')) {
            displayPackageName = displayPackageName.substring(5); // 去掉"java."前缀
          }
          
          return {
            key: item.filePath || `class_${idx}`,
            rank: idx + 1,
            className: item.className || 'Unknown',
            packageName: displayPackageName,
            filePath: item.filePath || '',
            fullName: item.fullClassName || `${item.packageName}.${item.className}`,
            totalLines: item.totalLines || 0,
            codeLines: item.codeLines || 0,
            language: item.language || '',
            fileSize: item.fileSize || 0
          };
        });
    }
    return [];
  })();

  // 组装方法级别数据Top10（基于真实API数据）
  const topMethodsData = (() => {
    if (volumeTopData?.methods && Array.isArray(volumeTopData.methods)) {
      return volumeTopData.methods.map((method: any, idx: number) => {
        // 处理包名：如果以"java."开头，则从java后面开始显示
        let displayPackageName = method.packageName || '';
        if (displayPackageName.startsWith('java.')) {
          displayPackageName = displayPackageName.substring(5); // 去掉"java."前缀
        }
        
        return {
          key: `${method.filePath}#${method.methodName}` || `method_${idx}`,
          rank: idx + 1,
          methodName: method.methodName || 'Unknown',
          className: method.className || '',
          packageName: displayPackageName,
          filePath: method.filePath || '',
          fullName: method.methodFullName || `${method.className}#${method.methodName}`,
          totalLines: method.totalLines || 0,
          codeLines: method.codeLines || 0,
          startLine: method.startLine || 0,
          endLine: method.endLine || 0,
          accessFlag: method.accessFlag || '',
          isEntry: method.isEntry || false,
          serviceName: method.serviceName || '',
          serviceType: method.serviceType || ''
        };
      });
    }
    return [];
  })();

  return (
    <div>
      <Card 
        title={chartType === 'treemap' ? '代码文件路径结构图' : '代码体量旭日图'}
        extra={
          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <Button 
              size="small" 
              onClick={() => {
                const canvas = document.querySelector('.echarts-for-react canvas') as HTMLCanvasElement;
                if (canvas) {
                  const url = canvas.toDataURL('image/png');
                  const link = document.createElement('a');
                  link.download = `${chartType === 'treemap' ? '代码文件路径结构图' : '代码体量旭日图'}.png`;
                  link.href = url;
                  link.click();
                }
              }}
            >
              下载图片
            </Button>
          </div>
        }
        style={{ marginBottom: '12px' }}
      >
        <div style={{ marginBottom: '16px' }}>
          {/* 控制条：视图切换 */}
          <div style={{ display: 'flex', gap: 16, alignItems: 'center', flexWrap: 'wrap' }}>
            <div>
              <span style={{ marginRight: 8, color: '#666', fontWeight: '500' }}>视图类型:</span>
              <Button.Group size="small">
                <Button 
                  type={chartType === 'treemap' ? 'primary' : 'default'} 
                  onClick={() => setChartType('treemap')}
                  icon={<span style={{fontSize: '12px'}}>⬛</span>}
                >
                  路径结构图
                </Button>
                <Button 
                  type={chartType === 'sunburst' ? 'primary' : 'default'} 
                  onClick={() => setChartType('sunburst')}
                  icon={<span style={{fontSize: '12px'}}>⭕</span>}
                >
                  旭日图
                </Button>
              </Button.Group>
            </div>
            <div style={{ color: '#999', fontSize: '12px' }}>
              💡 {chartType === 'treemap' ? '按文件路径层级展示，点击目录可下钻查看详情' : '鼠标悬停查看详情，点击重置恢复全貌'}
            </div>
          </div>
        </div>
        
        <div style={{ 
          border: '1px solid #f0f0f0', 
          borderRadius: '8px', 
          padding: '8px',
          backgroundColor: '#fafafa'
        }}>
          <ReactECharts 
            option={chartType === 'treemap' ? getTreemapOption() : getSunburstOption()} 
            style={{ width: '100%', height: '600px' }} 
            opts={{ renderer: 'canvas' }} 
          />
        </div>
      </Card>

      {/* 代码行数 Top 10 表格 */}
      <div style={{ display: 'flex', gap: '12px' }}>
        {/* 类级别 Top 10 */}
        <Card 
          title="类级别 Top 10 (按总行数降序)"
          style={{ flex: 1 }}
          bodyStyle={{ padding: '12px' }}
        >
          {volumeTopLoading ? (
            <div style={{ textAlign: 'center', padding: '20px' }}>
              <Spin />
              <div style={{ marginTop: '8px', fontSize: '12px' }}>加载中...</div>
            </div>
          ) : topClassesData.length > 0 ? (
            <Table
              dataSource={topClassesData}
              rowKey="key"
              pagination={false}
              size="small"
              showHeader={true}
              style={{ fontSize: '12px' }}
              columns={[
                { 
                  title: '排名', 
                  dataIndex: 'rank', 
                  key: 'rank', 
                  width: 45, 
                  align: 'center' as const,
                  render: (rank: number) => (
                    <div style={{ 
                      width: 18, 
                      height: 18, 
                      borderRadius: '50%', 
                      backgroundColor: rank <= 3 ? '#ff4d4f' : rank <= 6 ? '#faad14' : '#52c41a',
                      color: 'white',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      fontSize: 9,
                      fontWeight: 'bold',
                      margin: '0 auto'
                    }}>
                      {rank}
                    </div>
                  )
                },
                { 
                  title: '类名', 
                  dataIndex: 'className', 
                  key: 'className',
                  render: (text: string, record: any) => {
                    const giteeLink = buildGiteeLink(record.filePath);
                    return giteeLink ? (
                      <a 
                        href={giteeLink}
                        target="_blank"
                        rel="noopener noreferrer"
                        style={{ fontWeight: 'bold', color: '#1890ff', fontSize: '12px', textDecoration: 'none' }}
                        onMouseEnter={(e) => (e.target as HTMLElement).style.textDecoration = 'underline'}
                        onMouseLeave={(e) => (e.target as HTMLElement).style.textDecoration = 'none'}
                        title={`查看 ${text} 的源代码`}
                      >
                        {text}
                      </a>
                    ) : (
                      <div style={{ fontWeight: 'bold', color: '#1890ff', fontSize: '12px' }}>
                        {text}
                      </div>
                    );
                  }
                },
                { 
                  title: '文件路径', 
                  dataIndex: 'filePath', 
                  key: 'filePath',
                  render: (text: string) => (
                    <div style={{ fontSize: '10px', color: '#666' }}>
                      {text}
                    </div>
                  )
                },
                { 
                  title: '总行数', 
                  dataIndex: 'totalLines', 
                  key: 'totalLines', 
                  width: 60, 
                  align: 'center' as const,
                  render: (value: number) => (
                    <span style={{ fontWeight: '600', color: '#1890ff', fontSize: '12px' }}>{value || 0}</span>
                  )
                },
                { 
                  title: '代码行', 
                  dataIndex: 'codeLines', 
                  key: 'codeLines', 
                  width: 60, 
                  align: 'center' as const,
                  render: (value: number) => (
                    <span style={{ fontWeight: '600', color: '#52c41a', fontSize: '12px' }}>{value || 0}</span>
                  )
                }
              ]}
            />
          ) : (
            <div style={{ textAlign: 'center', padding: '20px' }}>
              <Empty description="暂无类数据" image={Empty.PRESENTED_IMAGE_SIMPLE} />
            </div>
          )}
        </Card>

        {/* 方法级别 Top 10 */}
        <Card 
          title="方法级别 Top 10 (按总行数降序)"
          style={{ flex: 1 }}
          bodyStyle={{ padding: '12px' }}
        >
          {volumeTopLoading ? (
            <div style={{ textAlign: 'center', padding: '20px' }}>
              <Spin />
              <div style={{ marginTop: '8px', fontSize: '12px' }}>加载中...</div>
            </div>
          ) : topMethodsData.length > 0 ? (
            <Table
              dataSource={topMethodsData}
              rowKey="key"
              pagination={false}
              size="small"
              showHeader={true}
              style={{ fontSize: '12px' }}
              columns={[
                { 
                  title: '排名', 
                  dataIndex: 'rank', 
                  key: 'rank', 
                  width: 45, 
                  align: 'center' as const,
                  render: (rank: number) => (
                    <div style={{ 
                      width: 18, 
                      height: 18, 
                      borderRadius: '50%', 
                      backgroundColor: rank <= 3 ? '#722ed1' : rank <= 6 ? '#1890ff' : '#13c2c2',
                      color: 'white',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      fontSize: 9,
                      fontWeight: 'bold',
                      margin: '0 auto'
                    }}>
                      {rank}
                    </div>
                  )
                },
                { 
                  title: '方法名', 
                  dataIndex: 'methodName', 
                  key: 'methodName',
                  render: (text: string, record: any) => {
                    const giteeLink = buildGiteeLink(record.filePath, record.startLine, record.endLine);
                    return giteeLink ? (
                      <a 
                        href={giteeLink}
                        target="_blank"
                        rel="noopener noreferrer"
                        style={{ fontWeight: 'bold', color: '#722ed1', fontSize: '12px', textDecoration: 'none' }}
                        onMouseEnter={(e) => (e.target as HTMLElement).style.textDecoration = 'underline'}
                        onMouseLeave={(e) => (e.target as HTMLElement).style.textDecoration = 'none'}
                        title={`查看方法 ${text} 的源代码${record.startLine ? ` (第${record.startLine}行)` : ''}`}
                      >
                        {text}
                      </a>
                    ) : (
                      <div style={{ fontWeight: 'bold', color: '#722ed1', fontSize: '12px' }}>
                        {text}
                      </div>
                    );
                  }
                },
                { 
                  title: '文件路径', 
                  dataIndex: 'filePath', 
                  key: 'filePath',
                  render: (text: string) => (
                    <div style={{ fontSize: '10px', color: '#666' }}>
                      {text}
                    </div>
                  )
                },
                { 
                  title: '总行数', 
                  dataIndex: 'totalLines', 
                  key: 'totalLines', 
                  width: 60, 
                  align: 'center' as const,
                  render: (value: number) => (
                    <span style={{ fontWeight: '600', color: '#722ed1', fontSize: '12px' }}>{value || 0}</span>
                  )
                },
                { 
                  title: '代码行', 
                  dataIndex: 'codeLines', 
                  key: 'codeLines', 
                  width: 60, 
                  align: 'center' as const,
                  render: (value: number) => (
                    <span style={{ fontWeight: '600', color: '#52c41a', fontSize: '12px' }}>{value || 0}</span>
                  )
                }
              ]}
            />
          ) : (
            <div style={{ textAlign: 'center', padding: '20px' }}>
              <Empty description="暂无方法数据" image={Empty.PRESENTED_IMAGE_SIMPLE} />
            </div>
          )}
        </Card>
      </div>
    </div>
  );
};

// 方法分析组件（原来的方法表格）
const MethodAnalysis: React.FC<{
    data: any[];
    pagination: any;
    loading: boolean;
    queryInfo: string;
    unitInfo: any;
    onSearch: (values: any, pager?: any) => void;
    onTableChange: (pager: any, filters: any, sorter: any) => void;
    onClearQuery: () => void;
}> = ({ data, pagination, loading, queryInfo, unitInfo, onSearch, onTableChange, onClearQuery }) => {
    return (
        <div>
            {/* 查询条件说明 */}
            {queryInfo && (
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
                    <Alert
                        message={queryInfo}
                        type="info"
                        showIcon
                        style={{ 
                            flex: 1,
                            backgroundColor: '#e6f7ff',
                            border: '1px solid #91d5ff',
                            margin: 0
                        }}
                        closable
                    />
                    <Button
                        type="link"
                        size="small"
                        onClick={onClearQuery}
                        style={{ color: '#1890ff' }}
                    >
                        清除条件
                    </Button>
                </div>
            )}
            
            <MethodFilterBar onSearch={onSearch} />
            
            <Spin spinning={loading}>
                <MethodTable 
                    data={data}
                    pagination={pagination}
                    loading={loading}
                    onChange={onTableChange}
                    unitInfo={unitInfo}
                />
            </Spin>
        </div>
    );
};

// 数据库分析组件
const DatabaseAnalysis: React.FC = () => {
    return (
        <div style={{ padding: '24px', textAlign: 'center' }}>
            <Empty 
                description="数据库分析功能开发中..." 
                image={Empty.PRESENTED_IMAGE_SIMPLE}
            />
        </div>
    );
};

// 扫描记录组件
const ScanRecords: React.FC = () => {
    return (
        <div style={{ padding: '24px', textAlign: 'center' }}>
            <Empty 
                description="扫描记录功能开发中..." 
                image={Empty.PRESENTED_IMAGE_SIMPLE}
            />
        </div>
    );
};

// 依赖分析组件
const DependencyAnalysis: React.FC = () => {
    return (
        <div style={{ padding: '24px', textAlign: 'center' }}>
            <Empty 
                description="依赖分析功能开发中..." 
                image={Empty.PRESENTED_IMAGE_SIMPLE}
            />
        </div>
    );
};

// 配置管理组件
const ConfigManagement: React.FC<{ unitInfo: any }> = ({ unitInfo }) => {
    if (!unitInfo) {
        return <Empty description="单元信息加载中..." />;
    }

    return (
        <div style={{ padding: '24px', background: '#f5f5f5', minHeight: '500px' }}>
            {/* 扫描任务配置 */}
            <Row gutter={[24, 24]}>
                <Col span={24}>
                    <Card 
                        title={
                            <span style={{ fontSize: '18px', fontWeight: '600' }}>
                                ⚙️ 扫描任务配置
                            </span>
                        }
                        style={{ 
                            borderRadius: '12px',
                            boxShadow: '0 4px 12px rgba(0,0,0,0.1)'
                        }}
                    >
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 0' }}>
                            <div style={{ display: 'flex', gap: '48px', flexWrap: 'wrap' }}>
                                <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                                    <span style={{ fontSize: '24px' }}>{unitInfo.saTask ? '✅' : '❌'}</span>
                                    <div>
                                        <div style={{ fontSize: '16px', fontWeight: '500', color: '#333' }}>SA扫描</div>
                                        <div style={{ fontSize: '12px', color: '#999' }}>静态分析扫描</div>
                                    </div>
                                </div>
                                <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                                    <span style={{ fontSize: '24px' }}>{unitInfo.gitTask ? '✅' : '❌'}</span>
                                    <div>
                                        <div style={{ fontSize: '16px', fontWeight: '500', color: '#333' }}>Git扫描</div>
                                        <div style={{ fontSize: '12px', color: '#999' }}>代码仓库扫描</div>
                                    </div>
                                </div>
                                <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                                    <span style={{ fontSize: '24px' }}>{unitInfo.apmTask ? '✅' : '❌'}</span>
                                    <div>
                                        <div style={{ fontSize: '16px', fontWeight: '500', color: '#333' }}>APM扫描</div>
                                        <div style={{ fontSize: '12px', color: '#999' }}>应用性能监控</div>
                                    </div>
                                </div>
                                <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                                    <span style={{ fontSize: '24px' }}>{unitInfo.jarTask ? '✅' : '❌'}</span>
                                    <div>
                                        <div style={{ fontSize: '16px', fontWeight: '500', color: '#333' }}>JAR扫描</div>
                                        <div style={{ fontSize: '12px', color: '#999' }}>依赖包分析</div>
                                    </div>
                                </div>
                            </div>
                            <div style={{ 
                                fontSize: '14px', 
                                color: '#666',
                                background: '#f0f0f0',
                                padding: '8px 16px',
                                borderRadius: '6px',
                                fontWeight: '500'
                            }}>
                                {[unitInfo.saTask, unitInfo.gitTask, unitInfo.apmTask, unitInfo.jarTask].filter(Boolean).length}/4 个任务已开启
                            </div>
                        </div>
                    </Card>
                </Col>
            </Row>

            {/* 单元基本配置 */}
            <Row gutter={[24, 24]} style={{ marginTop: 24 }}>
                <Col span={12}>
                    <Card 
                        title={
                            <span style={{ fontSize: '16px', fontWeight: '600' }}>
                                📝 基本配置
                            </span>
                        }
                        style={{ 
                            borderRadius: '12px',
                            boxShadow: '0 4px 12px rgba(0,0,0,0.1)'
                        }}
                    >
                        <div style={{ lineHeight: '2' }}>
                            <p style={{ margin: '12px 0', fontSize: '14px' }}>
                                <strong style={{ color: '#666' }}>单元ID：</strong>
                                <span style={{ color: '#333' }}>{unitInfo.unitId || '-'}</span>
                            </p>
                            <p style={{ margin: '12px 0', fontSize: '14px' }}>
                                <strong style={{ color: '#666' }}>应用ID：</strong>
                                <span style={{ color: '#333' }}>{unitInfo.appId || '-'}</span>
                            </p>
                            <p style={{ margin: '12px 0', fontSize: '14px' }}>
                                <strong style={{ color: '#666' }}>单元类型：</strong>
                                <span style={{ color: '#333' }}>{unitInfo.unitType || '-'}</span>
                            </p>
                            <p style={{ margin: '12px 0', fontSize: '14px' }}>
                                <strong style={{ color: '#666' }}>归属团队：</strong>
                                <span style={{ color: '#333' }}>{unitInfo.ownTeam || '-'}</span>
                            </p>
                            <p style={{ margin: '12px 0', fontSize: '14px' }}>
                                <strong style={{ color: '#666' }}>归属中心：</strong>
                                <span style={{ color: '#333' }}>{unitInfo.ownCenter || '-'}</span>
                            </p>
                        </div>
                    </Card>
                </Col>
                <Col span={12}>
                    <Card 
                        title={
                            <span style={{ fontSize: '16px', fontWeight: '600' }}>
                                🔗 Git仓库配置
                            </span>
                        }
                        style={{ 
                            borderRadius: '12px',
                            boxShadow: '0 4px 12px rgba(0,0,0,0.1)'
                        }}
                    >
                        <div style={{ lineHeight: '2' }}>
                            <p style={{ margin: '12px 0', fontSize: '14px' }}>
                                <strong style={{ color: '#666' }}>仓库地址：</strong>
                                {unitInfo.gitRepoUrl ? (
                                    <a 
                                        href={unitInfo.gitRepoUrl} 
                                        target="_blank" 
                                        rel="noopener noreferrer"
                                        style={{ color: '#1890ff', textDecoration: 'none' }}
                                    >
                                        {unitInfo.gitRepoUrl}
                                    </a>
                                ) : (
                                    <span style={{ color: '#333' }}>-</span>
                                )}
                            </p>
                            <p style={{ margin: '12px 0', fontSize: '14px' }}>
                                <strong style={{ color: '#666' }}>默认分支：</strong>
                                <span style={{ color: '#333' }}>{unitInfo.defaultBranch || '-'}</span>
                            </p>
                            <p style={{ margin: '12px 0', fontSize: '14px' }}>
                                <strong style={{ color: '#666' }}>仓库ID：</strong>
                                <span style={{ color: '#333' }}>{unitInfo.gitRepoId || '-'}</span>
                            </p>
                            <p style={{ margin: '12px 0', fontSize: '14px' }}>
                                <strong style={{ color: '#666' }}>制品库路径：</strong>
                                <span style={{ color: '#333' }}>{unitInfo.artifactoryPath || '-'}</span>
                            </p>
                        </div>
                    </Card>
                </Col>
            </Row>
        </div>
    );
};

const UnitDetailPage: React.FC<UnitDetailPageProps> = ({ unitId }) => {
    const [filter, setFilter] = useState<any>({});
    const [data, setData] = useState<any[]>([]);
    const [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 0 });
    const [loading, setLoading] = useState(false);
    const [unitInfo, setUnitInfo] = useState<any>(null);
    const [queryInfo, setQueryInfo] = useState<string>(''); // 查询条件说明
    const [activeTab, setActiveTab] = useState('basicInfo'); // 当前激活的tab，默认基本信息
    const [loadedTabs, setLoadedTabs] = useState<Set<string>>(new Set(['basicInfo'])); // 记录已加载的tab
    const navigate = useNavigate();

    const loadUnitInfo = useCallback(async () => {
        if (!unitId) return;
        try {
            console.log('Loading unit info for:', unitId);
            const res = await getUnit(unitId);
            console.log('Unit info response:', res);
            // 兼容不同返回结构 { data: {...} } 或直接 {...}
            const dataRes = (res && res.data) ? res.data : res;
            setUnitInfo(dataRes || null);
        } catch (e: any) {
            console.error('Failed to load unit info:', e);
            // 提供更详细的错误信息
            const errorMessage = e?.response?.data?.msg || e?.message || '加载单元信息失败';
            console.error('Error message:', errorMessage);
            setUnitInfo(null);
            // 可以在这里设置一个错误状态
        }
    }, [unitId]);

    const handleSearch = useCallback(async (values: any, pager = { current: 1, pageSize: 10, total: 0 }) => {
        setFilter(values);
        setLoading(true);
        
        // 构建基础参数
        const params: any = { unitId, pageNum: pager.current, pageSize: pager.pageSize };
        
        // 处理通用搜索（快速搜索）
        if (values._isQuickSearch) {
            // 快速搜索模式：在包名、类名、方法名中搜索关键词
            const keyword = values.packageName || values.className || values.methodName;
            if (keyword && keyword.trim()) {
                // 只传递一个关键词到后端，让后端在多个字段中搜索
                // 这里我们优先使用 methodName 字段作为通用搜索字段
                params.methodName = keyword.trim();
                // 如果后端支持通用搜索字段，可以改为：
                // params.keyword = keyword.trim();
            }
        } else {
            // 精确搜索模式：处理每个字段
            const stringFields = ['className', 'methodName', 'packageName', 'methodSignature', 'serviceName', 'serviceType', 'codeStatus', 'runtimeStatus'];
            stringFields.forEach(field => {
                if (values[field] && values[field].trim() !== '') {
                    params[field] = values[field].trim();
                }
            });
        }
        
        // 处理布尔字段：只有明确的true/false才传递
        if (values.isEntry !== undefined && values.isEntry !== null && values.isEntry !== '') {
            // 处理字符串形式的布尔值
            if (values.isEntry === 'true' || values.isEntry === true) {
                params.isEntry = true;
            } else if (values.isEntry === 'false' || values.isEntry === false) {
                params.isEntry = false;
            }
        }
        
        // 处理时间范围字段：将天数转换为具体的时间查询参数
        // 累计无调用时长（天）- 转换为最后调用时间的时间范围
        if (values.noSaCallDurationDays !== undefined && values.noSaCallDurationDays !== null && values.noSaCallDurationDays !== '') {
            const numValue = Number(values.noSaCallDurationDays);
            if (!isNaN(numValue) && numValue > 0) {
                // 使用工具函数计算对应的时间
                const timeQuery = convertDaysToDateQuery(numValue);
                
                // 添加调试信息
                console.log(`查询累计无调用时长 >= ${numValue}天，即最后调用时间在 ${timeQuery.formatDisplay} 之前`);
                
                // 如果后端支持时间范围查询，可以使用这些参数
                // params.lastInvocationTimeBefore = timeQuery.dateString; // YYYY-MM-DD格式
                // params.lastInvocationTimeBeforeTs = timeQuery.timestamp; // 时间戳格式
                
                // 目前仍然传递天数给后端，让后端处理具体的时间计算
                params.noSaCallDurationDays = numValue;
                
                // 可以将计算出的时间信息存储，供后续使用
                params._meta = params._meta || {};
                params._meta.noSaCallCutoffDate = timeQuery.formatDisplay;
            }
        }
        
        // 累计无修改时长（天）- 转换为最后修改时间的时间范围  
        if (values.noCodeChangeDurationDays !== undefined && values.noCodeChangeDurationDays !== null && values.noCodeChangeDurationDays !== '') {
            const numValue = Number(values.noCodeChangeDurationDays);
            if (!isNaN(numValue) && numValue > 0) {
                // 使用工具函数计算对应的时间
                const timeQuery = convertDaysToDateQuery(numValue);
                
                // 添加调试信息
                console.log(`查询累计无修改时长 >= ${numValue}天，即最后修改时间在 ${timeQuery.formatDisplay} 之前`);
                
                // 如果后端支持时间范围查询，可以使用这些参数
                // params.gitLastEditTimeBefore = timeQuery.dateString; // YYYY-MM-DD格式
                // params.gitLastEditTimeBeforeTs = timeQuery.timestamp; // 时间戳格式
                
                // 目前仍然传递天数给后端，让后端处理具体的时间计算
                params.noCodeChangeDurationDays = numValue;
                
                // 可以将计算出的时间信息存储，供后续使用
                params._meta = params._meta || {};
                params._meta.noCodeChangeCutoffDate = timeQuery.formatDisplay;
            }
        }
        
        // 处理排序字段
        if (values.orderBy && values.orderBy.trim() !== '') {
            params.orderBy = values.orderBy.trim();
        }
        if (values.orderByType && values.orderByType.trim() !== '') {
            params.orderByType = values.orderByType.trim();
        }
        
        // 生成查询条件说明
        const queryDescriptions: string[] = [];
        
        // 存储排序信息到meta中
        if (params.orderBy && params.orderByType) {
            params._meta = params._meta || {};
            params._meta.orderByType = params.orderByType;
        }

        // 检查是否为快速搜索
        if (values._isQuickSearch && params.methodName) {
            queryDescriptions.push(`通用搜索："${params.methodName}" (在包名、类名、方法名中查找)`);
        } else {
            // 处理所有查询条件
            Object.keys(params).forEach(key => {
                if (key === '_meta' || key === 'unitId' || key === 'pageNum' || key === 'pageSize' || key === 'orderByType') {
                    return; // 跳过元数据和分页参数
                }
                
                const value = params[key];
                if (value !== undefined && value !== null && value !== '') {
                    const description = formatQueryCondition(key, value, params._meta);
                    queryDescriptions.push(description);
                }
            });
        }
        
        // 设置查询说明
        if (queryDescriptions.length > 0) {
            setQueryInfo(`当前查询条件：${queryDescriptions.join('，')}`);
        } else {
            setQueryInfo('');
        }
        
        // 输出最终查询参数（用于调试）
        console.log('最终查询参数：', {
            ...params,
            _meta: params._meta || {}
        });
        
        // 移除元数据，不发送给后端
        if (params._meta) {
            delete params._meta;
        }
        
        const res = await fetchMethodPageQuery(params);
        const dataRes = res.data || res;
        setData(dataRes.records || []);
        setPagination({ ...pager, total: dataRes.total || 0 });
        setLoading(false);
    }, [unitId]);

    useEffect(() => {
        if (unitId) {
            loadUnitInfo();
            handleSearch({}, { current: 1, pageSize: 10, total: 0 });
        }
    }, [unitId, handleSearch, loadUnitInfo]);

    // 表格排序、分页、筛选事件
    const handleTableChange = (pager: any, filters: any, sorter: any) => {
        let orderBy, orderByType;
        if (sorter && sorter.field && sorter.order) {
            orderBy = sorter.field;
            orderByType = sorter.order === 'ascend' ? 'asc' : 'desc';
        }
        handleSearch(
            { ...filter, orderBy, orderByType },
            { current: pager.current, pageSize: pager.pageSize, total: pagination.total }
        );
    };

    // 处理tab切换，标记已加载的tab
    const handleTabChange = (key: string) => {
        setActiveTab(key);
        setLoadedTabs(prev => new Set(Array.from(prev).concat(key)));
    };

    return (
        <div style={{ margin: '24px', background: '#fff', padding: 24, borderRadius: 10, boxShadow: '0 2px 8px #f0f1f2' }}>
            <Button
                type="default"
                onClick={() => {
                    if (window.history.length > 1) {
                        window.history.back();
                    } else {
                        navigate('/units');
                    }
                }}
                style={{ marginBottom: 16 }}
            >
                返回
            </Button>
            

            
            <div style={{ display: 'flex', alignItems: 'center', marginBottom: 12 }}>
                <span style={{ fontSize: 22, fontWeight: 700, color: '#222', marginRight: 16 }}>单元：{unitId}</span>
            </div>
            
            {/* Tab导航 */}
            <Tabs
                activeKey={activeTab}
                onChange={handleTabChange}
                size="large"
                style={{
                    minHeight: '600px'
                }}
                tabBarStyle={{
                    marginBottom: 0,
                    borderBottom: '2px solid #f0f0f0'
                }}
                items={[
                    {
                        key: 'basicInfo',
                        label: (
                            <span>
                                <InfoCircleOutlined />
                                基本信息
                            </span>
                        ),
                        children: <BasicInfo unitId={unitId} />
                    },
                    {
                        key: 'codeScaleAnalysis',
                        label: (
                            <span>
                                <BarChartOutlined />
                                体量分析
                            </span>
                        ),
                        children: loadedTabs.has('codeScaleAnalysis') ? <CodeScaleAnalysis unitId={unitId} /> : null
                    },
                    {
                        key: 'methodAnalysis',
                        label: (
                            <span>
                                <FunctionOutlined />
                                方法分析
                            </span>
                        ),
                        children: loadedTabs.has('methodAnalysis') ? (
                            <MethodAnalysis
                                data={data}
                                pagination={pagination}
                                loading={loading}
                                queryInfo={queryInfo}
                                unitInfo={unitInfo}
                                onSearch={(values, pager) => handleSearch(values, pager || { current: 1, pageSize: pagination.pageSize, total: pagination.total })}
                                onTableChange={handleTableChange}
                                onClearQuery={() => {
                                    setQueryInfo('');
                                    handleSearch({}, { current: 1, pageSize: pagination.pageSize, total: 0 });
                                }}
                            />
                        ) : null
                    },
                    {
                        key: 'apiAnalysis',
                        label: (
                            <span>
                                <ApiOutlined />
                                API分析
                            </span>
                        ),
                        children: loadedTabs.has('apiAnalysis') ? <ApiAnalysis /> : null
                    },
                    {
                        key: 'databaseAnalysis',
                        label: (
                            <span>
                                <DatabaseOutlined />
                                数据库
                            </span>
                        ),
                        children: loadedTabs.has('databaseAnalysis') ? <DatabaseAnalysis /> : null
                    },
                    {
                        key: 'scanRecords',
                        label: (
                            <span>
                                <FileTextOutlined />
                                扫描记录
                            </span>
                        ),
                        children: loadedTabs.has('scanRecords') ? <ScanRecords /> : null
                    },
                    {
                        key: 'dependencyAnalysis',
                        label: (
                            <span>
                                <BarChartOutlined />
                                依赖分析
                            </span>
                        ),
                        children: loadedTabs.has('dependencyAnalysis') ? <DependencyAnalysis /> : null
                    },
                    {
                        key: 'configManagement',
                        label: (
                            <span>
                                <SettingOutlined />
                                配置
                            </span>
                        ),
                        children: loadedTabs.has('configManagement') ? <ConfigManagement unitInfo={unitInfo} /> : null
                    }
                ]}
            />
        </div>
    );
};

export default UnitDetailPage; 